<template>
  <!-- 这是简单的用法 -->
  <button @click="nextPage++">
    下一页 一共{{ nextPage }} {{ pdfPages }}页
  </button>
  <div class="interviewVideo_main" id="videoContainer">
    <!--此处根据pdf的页数动态生成相应数量的canvas画布-->
    <canvas
      v-for="pageIndex in pdfPages"
      :id="`the-canvas` + pageIndex"
      :key="pageIndex"
      style="display: block"
    ></canvas>
  </div>
</template>
<script setup>
import { ref, reactive, onMounted, nextTick, watch } from "vue";
import * as pdfjsLib from "pdfjs-dist/build/pdf";
let pdfDoc = reactive({}); // 保存加载的pdf文件流
let pdfPages = ref(0); // pdf文件的页数
let pdfUrl = ref("/test.pdf"); //pdf文件的链接
let pdfScale = ref(0.5); // 缩放比例
const nextPage = ref(1);
//调用loadFile方法
onMounted(() => {
  loadFile(pdfUrl.value);
});
//获取pdf文档流与pdf文件的页数
const loadFile = async (url) => {
  pdfjsLib.GlobalWorkerOptions.workerSrc =
    "https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.9.179/pdf.worker.min.js";
  const loadingTask = pdfjsLib.getDocument(url);
  loadingTask.promise.then((pdf) => {
    console.log(pdf);
    pdfDoc = pdf;
    pdfPages.value = pdf.numPages;
    nextTick(() => {
      renderPage(nextPage.value);
    });
  });
};
watch(nextPage, (newval) => {
  renderPage(newval);
});
//渲染pdf文件
const renderPage = function (num) {
  pdfDoc.getPage(num).then((page) => {
    let canvas = document.getElementById("the-canvas" + num);
    let ctx = canvas.getContext("2d");
    let dpr = window.devicePixelRatio || 1;
    let bsr =
      ctx.webkitBackingStorePixelRatio ||
      ctx.mozBackingStorePixelRatio ||
      ctx.msBackingStorePixelRatio ||
      ctx.oBackingStorePixelRatio ||
      ctx.backingStorePixelRatio ||
      1;
    let ratio = dpr / bsr;
    let viewport = page.getViewport({
      scale: screen.availWidth / page.getViewport({ scale: 2 }).width,
    });
    //
    canvas.width = viewport.width * ratio;
    canvas.height = viewport.height * ratio;
    canvas.style.width = viewport.width + "px";
    canvas.style.height = viewport.height + "px";
    ctx.setTransform(ratio, 0, 0, ratio, 0, 0);
    let renderContext = {
      canvasContext: ctx,
      viewport: viewport,
    };
    page.render(renderContext);
  });
};
</script>
<style>
#videoContainer {
  height: 842px;
}
</style>
